﻿using PLCS.Application.Contracts.HisTaskApp;
using PLCS.Application.Contracts.HisTaskApp.Dtos;
using PLCS.Application.Contracts.TaskApp.Dtos;
using PLCS.Domain.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.HisTaskApp;

public class HisInstructionAppService : CrudAppService<HisInstruction, HisInstructionDto, Guid, PagedResultRequestDto, HisInstructionDto>, IHisInstructionAppService
{
    public HisInstructionAppService(IRepository<HisInstruction, Guid> repository) : base(repository)
    {
    }

    public async Task<PagedResultDto<HisInstructionDto>> GetListBySearchAsync(PagedResultRequestDto input, string? instructionNo, string? StartTime, string? EndTime)
    {
        await CheckGetListPolicyAsync();

        var query = await CreateFilteredQueryAsync(input);
        query = query.OrderByDescending(x => x.CreationTime);
        bool isInstructionNo = int.TryParse(instructionNo, out int intInstructionNo);
        query = query.WhereIf(isInstructionNo, x => x.InstructionNo == intInstructionNo);
        bool isStartTime = DateTime.TryParse(StartTime, out DateTime StartDateTime);
        query = query.WhereIf(isStartTime, x => x.CreationTime > StartDateTime);
        bool isEndTime = DateTime.TryParse(EndTime, out DateTime EndDateTime);
        query = query.WhereIf(isEndTime, x => x.CreationTime < EndDateTime);
        var totalCount = await AsyncExecuter.CountAsync(query);

        query = ApplyPaging(query, input);

        var entities = await AsyncExecuter.ToListAsync(query);
        var entityDtos = await MapToGetListOutputDtosAsync(entities);

        return new PagedResultDto<HisInstructionDto>(
            totalCount,
            entityDtos
        );
    }
}